var csv = require('./lib/ya-csv')
var path = require('path')
var fs = require('fs')
var lotteryData;

function lotteryDataInit() {
    lotteryData = {
        currentStep: -1,
        items: [],
        videos: [
            './assets/WC TEAM.mp4'
        ],
        lotteryResult: [

        ],
        targetResult: [
            {
                key: 12,
                value: 'Client Service Systems'
            },
            {
                key: 32,
                value: 'Marketing'
            },
            {
                key: 39,
                value: 'Product Development'
            },
            {
                key: 49,
                value: 'Service Delivery'
            },
            {
                key: 11,
                value: 'Client Service'
            },
            {
                key: 15,
                value: 'Core Operations'
            },
            {
                key: 23,
                value: 'Front Office Systems'
            },
            {
                key: 27,
                value: 'Hong Kong Intermediary & Direct Sales'
            }
        ]
    }
}


function loadData() {
    var curPath = path.dirname(path.resolve(process.execPath));
    var srcPath;
    if (!fs.existsSync(curPath + '/srcData/DataB.csv')) {
        srcPath = './data/DataB.csv';
    }
    else {
        srcPath = curPath + '/srcData/DataB.csv'
    }
    var reader = csv.createCsvFileReader(srcPath, {
        'separator': ',',
        'quote': '"',
        'escape': '"',
        'comment': '',
    });
    reader.addListener('data', function (data) {
        lotteryData.items.push(data)
    }); 
}

function writeData(dataArr) {
    var curPath = path.dirname(path.resolve(process.execPath));
    if (!fs.existsSync(curPath + '/data')) {
        fs.mkdirSync(curPath + '/data')
    }
    //var writer = csv.createCsvFileWriter(curPath + '/data/dataResultA.csv');
    // var csvRecord = '';
    // lotteryData.lotteryResult.forEach(dateItem => {
    //     csvRecord += dateItem[0].replace(/,/g,' ') + ',' + dateItem[1] + '\n'
    // })
    // writer.writeRecord(csvRecord);
    fs.appendFileSync(curPath + '/data/dataResultB.csv', dataArr[0].replace(/,/g, ' ') + ',' + dataArr[1] + ',' + (new Date().toLocaleString()) + '\n')
}

function deleteData() {
    var curPath = path.dirname(path.resolve(process.execPath));
    if (fs.existsSync(curPath + '/data/dataResultB.csv')) {
        fs.unlinkSync(curPath + '/data/dataResultB.csv')
    }
}

lotteryDataInit()
loadData()

var lotteryVideoIndex = 0;
var lotterVideoMaxIndex = lotteryData.videos.length;//此处不减1 后面判断则不需减一
function getVideo() {
    var result = lotteryData.videos[lotteryVideoIndex]
    if (lotteryVideoIndex + 1 < lotterVideoMaxIndex) {
        lotteryVideoIndex++;
    } else {
        //若溢出则回归0
        lotteryVideoIndex = 0;
    }
    return result;
}
var isRunning = false;
var isReady = true;
function nextStep() {
    if (!isRunning) {
        if (!isReady) {
            var videoElement = document.querySelector('#mainVideo')
            videoElement.src = ''
            videoElement.src = './assets/hand_button.mp4'
            showResult(0);
            isReady = true;
        } else {
            showResult(0);
            isRunning = true;
            var videoElement = document.querySelector('#mainVideo')
            videoElement.play();
            videoElement.currentTime = 1
        }
    }
}
var videoState = 'handbutton' || 'wordcloud'
function mainVideoEnded() {
    switch (videoState) {
        case "handbutton":
            playWordcloud()
            videoState = 'wordcloud'
            break;
        case "wordcloud":
            isRunning = false;
            isReady = false;
            videoState = 'handbutton'
            break;
    }
}

function playWordcloud() {
    showResult(0);
    lotteryData.currentStep++;
    var videoUrl = getVideo();
    var videoElement = document.querySelector('#mainVideo')
    videoElement.src = videoUrl;
    videoElement.play();
    setTimeout(() => {
        videoEnded();
    }, 7 * 1000);
}


function reSet() {
    if (confirm("Are you sure reset")) {
        showResult(0);
        lotteryDataInit();
        loadData();
        var videoElement = document.querySelector('#mainVideo')
        videoElement.src = './assets/hand_button.mp4';
        // videoElement.setAttribute('loop')
        isPlaying = false;
        isReady = true
        deleteData()
    }
}

function videoEnded() {
    var resultData;
    if (lotteryData.currentStep < 8) {
        resultData = computLottery(lotteryData.items, lotteryData.targetResult[lotteryData.currentStep])
    } else {
        resultData = computLottery(lotteryData.items)
    }

    lotteryData.items = resultData.data
    lotteryData.lotteryResult.push(resultData.lotteryData[0])
    showResult(1, resultData.lotteryData[0]);
    writeData(resultData.lotteryData[0])
}

function showResult(isShow, text) {
    var resultElement = document.querySelector('#displayResult')
    if (isShow) {
        resultElement.classList.add('showResultAnimationB')
        resultElement.style['display'] = 'block'
        var name = text[0]
        var teamName = text[1]
        setTimeout(() => {
            resultElement.innerHTML = "<h2><b>" + teamName + "</b></h2>";
            resultElement.style['min-width'] = '800px'
            resultElement.style['min-height'] = '150px'
        }, 1000);
    } else {
        resultElement.classList.remove('showResultAnimationB')
        resultElement.style['display'] = 'none'
        resultElement.style['min-width'] = '0'
        resultElement.style['min-height'] = '0'
        resultElement.innerHTML = ''
    }
}


